<template>
  <div>
    <el-page-header :icon="null" title="文档管理" content="管理系统中的所有文档" />
    
    <!-- 搜索和操作区 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文档..."
          prefix-icon="Search"
          @input="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="12">
        <div style="text-align: right;">
          <el-button type="primary" @click="$router.push('/documents/upload')">
            <el-icon><Upload /></el-icon>
            上传文档
          </el-button>
          <el-button @click="refreshDocuments">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 文档列表 -->
    <el-card style="margin-top: 20px;">
      <el-table 
        :data="documents" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="文档名称" min-width="200">
          <template #default="{ row }">
            <el-link @click="viewDocument(row)">{{ row.name || row.fileName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="文件类型" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ row.type || getFileType(row.fileName) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="文件大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="permission" label="权限" width="100">
          <template #default="{ row }">
            <el-tag :type="getPermissionType(row.permission)" size="small">
              {{ getPermissionText(row.permission) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="最后修改" width="160">
          <template #default="{ row }">
            {{ formatTime(row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看详情" placement="top" :hide-after="0">
                <button 
                  class="modern-btn view-btn"
                  @click="viewDocument(row)"
                >
                  <el-icon><View /></el-icon>
                </button>
              </el-tooltip>
              <el-tooltip content="切换权限" placement="top" :hide-after="0">
                <button 
                  class="modern-btn switch-btn"
                  @click="togglePermission(row)"
                >
                  <el-icon><Lock /></el-icon>
                </button>
              </el-tooltip>
              <el-tooltip content="删除文档" placement="top" :hide-after="0">
                <button 
                  class="modern-btn delete-btn"
                  @click="deleteDocument(row.id)"
                >
                  <el-icon><Delete /></el-icon>
                </button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div v-if="selectedDocuments.length > 0" style="margin-top: 15px;">
        <el-alert 
          :title="`已选择 ${selectedDocuments.length} 个文档`" 
          type="info" 
          :closable="false"
        >
          <el-button type="danger" size="small" @click="batchDelete">批量删除</el-button>
          <el-button size="small" @click="batchUpdateStatus('active')">批量激活</el-button>
          <el-button size="small" @click="batchUpdateStatus('inactive')">批量禁用</el-button>
        </el-alert>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="totalPages > 1"
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalDocuments"
        layout="prev, pager, next, sizes, total"
        @current-change="changePage"
        style="margin-top: 20px; text-align: center;"
      />
    </el-card>

    <!-- 文档详情对话框 -->
    <el-dialog
      v-model="showDocumentModal"
      title="文档详情"
      width="600px"
      center
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      destroy-on-close
    >
      <div v-if="selectedDoc">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="文档名称">
            {{ selectedDoc.name || selectedDoc.fileName }}
          </el-descriptions-item>
          <el-descriptions-item label="文件类型">
            <el-tag size="small">{{ selectedDoc.type || getFileType(selectedDoc.fileName) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            {{ formatFileSize(selectedDoc.size) }}
          </el-descriptions-item>
          <el-descriptions-item label="权限">
            <el-tag :type="getPermissionType(selectedDoc.permission)">
              {{ getPermissionText(selectedDoc.permission) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(selectedDoc.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatTime(selectedDoc.updatedAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>

import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Upload, Refresh, View, Delete, Lock } from '@element-plus/icons-vue'
import { documentApi } from '@/api/document'

// 切换权限
const togglePermission = async (row) => {
  const newPermission = row.permission === 'public' ? 'private' : 'public';
  try {
    await documentApi.updateDocumentPermission(row.id, newPermission);
    ElMessage.success(`已切换为${getPermissionText(newPermission)}`);
    fetchDocuments();
  } catch (error) {
    ElMessage.error('切换权限失败');
  }
}

const documents = ref([])
const loading = ref(false)
const searchQuery = ref('')
const selectedDocuments = ref([])
const showDocumentModal = ref(false)
const selectedDoc = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const totalDocuments = ref(0)

const totalPages = computed(() => Math.ceil(totalDocuments.value / pageSize.value))

// 处理选中变化
const handleSelectionChange = (selection) => {
  selectedDocuments.value = selection.map(item => item.id)
}

// 获取文档列表
const fetchDocuments = async () => {
  loading.value = true
  try {
    const result = await documentApi.getAllDocuments()
    documents.value = Array.isArray(result) ? result : (result.data || [])
    totalDocuments.value = result.total || documents.value.length
  } catch (error) {
    console.error('获取文档列表失败:', error)
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索文档
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    fetchDocuments()
    return
  }
  
  loading.value = true
  try {
    const result = await documentApi.searchDocumentsByTitle(searchQuery.value)
    documents.value = Array.isArray(result) ? result : (result.data || [])
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 查看文档详情
const viewDocument = (doc) => {
  selectedDoc.value = doc
  showDocumentModal.value = true
}

// 删除文档
const deleteDocument = async (docId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个文档吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await documentApi.deleteDocument(docId)
    await fetchDocuments()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedDocuments.value.length} 个文档吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    for (const docId of selectedDocuments.value) {
      await documentApi.deleteDocument(docId)
    }
    selectedDocuments.value = []
    await fetchDocuments()
    ElMessage.success('批量删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量更新状态
const batchUpdateStatus = async (status) => {
  try {
    for (const docId of selectedDocuments.value) {
      await documentApi.updateDocumentStatus(docId, status)
    }
    selectedDocuments.value = []
    await fetchDocuments()
    ElMessage.success('批量更新成功')
  } catch (error) {
    console.error('批量更新失败:', error)
    ElMessage.error('批量更新失败')
  }
}

// 刷新文档列表
const refreshDocuments = () => {
  searchQuery.value = ''
  selectedDocuments.value = []
  fetchDocuments()
}

// 换页
const changePage = (page) => {
  currentPage.value = page
  fetchDocuments()
}

// 工具函数
const getFileType = (fileName) => {
  if (!fileName) return '未知'
  const ext = fileName.split('.').pop()?.toLowerCase()
  return ext || '未知'
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

const formatTime = (time) => {
  if (!time) return '无'
  return new Date(time).toLocaleString('zh-CN')
}

const getPermissionType = (permission) => {
  const typeMap = {
    public: 'success',
    private: 'warning'
  }
  return typeMap[permission] || 'info'
}

const getPermissionText = (permission) => {
  const permissionMap = {
    public: '公共',
    private: '私有'
  }
  return permissionMap[permission] || permission
}

onMounted(() => {
  fetchDocuments()
})
</script>

<style scoped>
.action-buttons {
  display: flex;
  gap: 6px;
  justify-content: center;
  align-items: center;
  padding: 6px 0;
}

/* 现代化椭圆形按钮基础样式 */
.modern-btn {
  width: 36px;
  height: 24px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0.0, 0.2, 1);
  position: relative;
  overflow: hidden;
  font-size: 0;
  outline: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transform: scale(1);
}

.modern-btn:hover {
  transform: scale(1.05) translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modern-btn:active {
  transform: scale(0.95);
  transition: transform 0.1s ease;
}

/* 查看按钮 - 蓝色椭圆 */
.view-btn {
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  color: white;
}

.view-btn:hover {
  background: linear-gradient(135deg, #5BA0F2 0%, #4A8ACD 100%);
  box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
}

/* 删除按钮 - 红色椭圆 */
.delete-btn {
  background: linear-gradient(135deg, #D0021B 0%, #B71C1C 100%);
  color: white;
}

.delete-btn:hover {
  background: linear-gradient(135deg, #E0122B 0%, #C72C2C 100%);
  box-shadow: 0 4px 12px rgba(208, 2, 27, 0.3);
}

/* 按钮图标样式 */
.modern-btn .el-icon {
  font-size: 14px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 点击波纹效果 */
.modern-btn::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.6s ease-out, height 0.6s ease-out;
}

.modern-btn:active::before {
  width: 40px;
  height: 40px;
}

/* 悬停光泽效果 */
.modern-btn::after {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  border-radius: 14px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.modern-btn:hover::after {
  opacity: 1;
}

/* 聚焦状态 */
.modern-btn:focus {
  box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.3);
}

/* 工具提示优化 */
.el-tooltip__popper {
  background: rgba(0, 0, 0, 0.85) !important;
  border: none !important;
  border-radius: 8px !important;
  font-size: 12px !important;
  font-weight: 500 !important;
  padding: 8px 12px !important;
  backdrop-filter: blur(4px) !important;
}

.el-tooltip__popper[data-popper-placement^="top"] .el-popper__arrow::before {
  background: rgba(0, 0, 0, 0.85) !important;
  border: none !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .modern-btn {
    width: 32px;
    height: 22px;
    border-radius: 11px;
  }
  
  .modern-btn .el-icon {
    font-size: 12px;
  }
  
  .action-buttons {
    gap: 4px;
  }
}

/* 按钮禁用状态 */
.modern-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}

.modern-btn:disabled:hover {
  transform: none !important;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
}

/* 文档详情对话框样式优化 */
:deep(.el-dialog) {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

:deep(.el-dialog__header) {
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  border-radius: 12px 12px 0 0;
}

:deep(.el-dialog__title) {
  color: #ffffff;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-dialog__headerbtn) {
  top: 16px;
  right: 20px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #ffffff;
  font-size: 16px;
}

:deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  color: #f1f5f9;
}

:deep(.el-dialog__body) {
  padding: 24px;
  background-color: #ffffff;
  border-radius: 0 0 12px 12px;
}

:deep(.el-descriptions) {
  margin: 0;
}

:deep(.el-descriptions__header) {
  margin-bottom: 16px;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

:deep(.el-descriptions__body) {
  background-color: #ffffff;
}

:deep(.el-descriptions__table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-descriptions-item__cell) {
  padding: 12px 16px;
  border-color: #f3f4f6;
}

:deep(.el-descriptions-item__label) {
  background-color: #f9fafb;
  font-weight: 500;
  color: #374151;
}

:deep(.el-descriptions-item__content) {
  background-color: #ffffff;
  color: #1f2937;
}
/* 切换权限按钮 - 黄色椭圆 */
.switch-btn {
  background: linear-gradient(135deg, #fbbf24 0%, #f59e42 100%);
  color: white;
}
.switch-btn:hover {
  background: linear-gradient(135deg, #fcd34d 0%, #fbbf24 100%);
  box-shadow: 0 4px 12px rgba(251, 191, 36, 0.3);
}
</style>
